/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 */

package com.example.omsdkdemo.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.device.idea.om.controller.model.AppUsageStats;
import com.example.omsdkdemo.R;

import java.util.List;

/**
 * 功能描述
 *
 * @since 2023-02-02
 */
public class AppUsageAdapter extends RecyclerView.Adapter<AppUsageAdapter.AppUsageViewHolder> {
    private final List<AppUsageStats> appUsageStats;

    public AppUsageAdapter(List<AppUsageStats> appUsageStats) {
        this.appUsageStats = appUsageStats;
        updateList(appUsageStats);
    }

    /**
     * updateList
     *
     * @param newList newList
     */
    public void updateList(List<AppUsageStats> newList) {
        appUsageStats.clear();
        appUsageStats.addAll(newList);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public AppUsageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.app_usage_item, parent, false);
        return new AppUsageViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull AppUsageViewHolder holder, int position) {
        AppUsageStats stats = appUsageStats.get(position);
        holder.packageName.setText(stats.getPackageName());
        holder.lastUsedTime.setText(String.valueOf(stats.getLastTimeUsed()));
        holder.totalTimeInForeground.setText(String.valueOf(stats.getTotalTimeInForeground()));
        holder.totalTimeVisible.setText(String.valueOf(stats.getTotalTimeVisible()));
        holder.totalTimeForegroundServiceUsed.setText(String.valueOf(stats.getTotalTimeForegroundServiceUsed()));
    }

    @Override
    public int getItemCount() {
        return appUsageStats.size();
    }

    /**
     * ViewHolder
     *
     * @since 2023-02-02
     */
    static class AppUsageViewHolder extends RecyclerView.ViewHolder {
        private TextView packageName;

        private TextView lastUsedTime;

        private TextView totalTimeInForeground;

        private TextView totalTimeVisible;

        private TextView totalTimeForegroundServiceUsed;

        AppUsageViewHolder(@NonNull View itemView) {
            super(itemView);
            packageName = itemView.findViewById(R.id.app_usage_packageName);
            lastUsedTime = itemView.findViewById(R.id.app_usage_lastUsedTime);
            totalTimeInForeground = itemView.findViewById(R.id.app_usage_totalTimeInForeground);
            totalTimeVisible = itemView.findViewById(R.id.app_usage_totalTimeVisible);
            totalTimeForegroundServiceUsed = itemView.findViewById(R.id.app_usage_totalTimeForegroundServiceUsed);
        }
    }
}
